package com.ophiux.transaction;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

/**
 * @desc: 本地事务监听器
 * @author: hhl
 * @date：2023/8/17 16:16
 */
public class TransactionListenerImpl implements TransactionListener {


    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        System.out.println("执行本地事务");
        String tags = message.getTags();
        if (StringUtils.contains("A", tags)) {
            //允许发送到消费者
            return LocalTransactionState.COMMIT_MESSAGE;
        }
        if (StringUtils.contains("B", tags)) {
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }else{
            return LocalTransactionState.UNKNOW;
        }
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        System.out.println("检查本地事务");
        String tags = messageExt.getTags();
        if (StringUtils.contains("C", tags)) {
            return LocalTransactionState.COMMIT_MESSAGE;
        }
        if (StringUtils.contains("D", tags)) {
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }else{
            return LocalTransactionState.UNKNOW;
        }
    }
}
